<script>
export default {
    name: "ProductAttr"
}
</script>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Goods_Specs } from '@/api';

// 搜索
let searchForm = reactive({
    rule_name: '',
})
let handleSearchRule = async () => {
    let { status, data } = await Goods_Specs.rule_list(searchForm);
    if (status === 200) {
        specsData.value = data.list;
    }
}

// 表格数据
let specsData = ref([])
let rule_list = async () => {
    let { status, msg, data } = await Goods_Specs.rule_list();
    if (status === 200) {
        specsData.value = data.list;
    }
}
let selected_ids = ref([])
let handleSelectionChange = (val) => {
    let ids = [];
    val.forEach(item => {
        ids.push(item.id);
    })
    selected_ids.value = ids;
}

// 添加规格模板
let goods_rule_visible = ref(false)
let addRuleForm = reactive({
    rule_name: '',
})
let addRuleRules = reactive({
    rule_name: [
        { required: true, message: '请输入规格名称', trigger: 'blur' },
    ],
})
let rule_content = ref(true)
// 标签设置
let spec = ref([])
let value = ref('')
let detail = ref([])
let ruleNum = ref('')
let inputValue = ref([])
let InputRef = ref('')
let addNewSpecs = () => {
    detail.value.push(ruleNum.value);
    let rule = Object.assign({}, { value: value.value }, { detail: detail.value });
    if (rule.value) {
        spec.value.push(rule);
        rule_content.value = true;
        detail.value = [];
    } else {
        ElMessage.error("请输入对应的值！");
    }
}
let handleSpecNameClose = (tag, detail) => {
    let index = detail.indexOf(tag);
    detail.splice(index, 1);
}
let handleValueClose = (item, spec) => {
    let index = spec.findIndex(tag => tag.value === item);
    spec.splice(index, 1);
}
let handleInputConfirm = (detail, index) => {
    if (inputValue.value[index]) {
        detail.push(inputValue.value[index])
    }
    inputValue.value[index] = ''
}
let handleAddNewRule = () => {
    value.value = '';
    ruleNum.value = '';
    rule_content.value = false;
}

// 添加
let handleAddGoodsRule = async () => {
    let { status, msg } = await Goods_Specs.set_rule(0, { rule_name: addRuleForm.rule_name, spec: spec.value });
    if (status === 200) {
        ElMessage.success(msg);
        goods_rule_visible.value = false;
        rule_list();
    }
}
// 编辑
let id = ref('')
let handleEditRule = (rule) => {
    addRuleForm.rule_name = rule.rule_name;
    spec.value = JSON.parse(rule.rule_value);
    id.value = rule.id;
    goods_rule_visible.value = true;
}
let handleEditGoodsRule = async () => {
    let { status, msg } = await Goods_Specs.set_rule(id.value, { rule_name: addRuleForm.rule_name, spec: spec.value });
    if (status === 200) {
        ElMessage.success(msg);
        rule_list();
        goods_rule_visible.value = false;
    }
}
// 删除
let handleDelRule = (rule, index) => {
    ElMessageBox.confirm(
        '确定要删除规格吗？',
        '删除规格',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let { status, msg } = await Goods_Specs.del_rules({ ids: rule.id });
            if (status === 200) {
                ElMessage.success(msg);
                specsData.value.splice(index, 1);
                goods_rule_visible.value = false;
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消该操作！',
            })
        })
}
// 批量删除
let handleBatchDel = async () => {
    if (selected_ids.value.length) {
        let ids = selected_ids.value.toString();
        let { status, msg } = await Goods_Specs.del_rules({ ids });
        if (status === 200) {
            ElMessage.success(msg);
            // 操作DOM
            rule_list();
        }
    } else {
        ElMessage.error("请选择要删除的商品规格！");
    }
}
// 重置表单
let set_rule = ref(null)
let handleResetForm = () => {
    set_rule.value.resetFields();
    spec.value = [];
    id.value = '';
    addRuleForm.rule_name = '';
}

onMounted(() => {
    rule_list();
})
</script>

<template>
    <el-card shadow="never">
        <el-form :model="searchForm" class="search-form">
            <el-form-item label="规格搜索：">
                <el-input v-model="searchForm.rule_name" placeholder="请输入规格名称" style="width:300px;">
                    <template #append>
                        <el-button icon="Search" @click="handleSearchRule" />
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <el-button type="primary" icon="Plus" style="margin-right: 15px;"
            @click="goods_rule_visible = true">添加商品规格</el-button>
        <el-button @click="handleBatchDel">批量删除</el-button>
        <el-table class="table" :data="specsData" @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#f4f3f9', color: '#606266' }" :row-style="{ height: '50px' }">
            <el-table-column type="selection" />
            <el-table-column property="id" label="ID" />
            <el-table-column property="rule_name" label="规格名称" />
            <el-table-column property="attr_name" label="商品规格" />
            <el-table-column property="attr_value" label="商品属性" width="400" />
            <el-table-column fixed="right" label="操作">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEditRule(scope.row)">编辑</el-button>
                    <el-divider direction="vertical" />
                    <el-button link type="primary" size="small"
                        @click="handleDelRule(scope.row, scope.$index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

    <!-- 添加/编辑商品规格 -->
    <el-dialog v-model="goods_rule_visible" title="商品规格" @close="handleResetForm">
        <el-form :model="addRuleForm" :rules="addRuleRules" ref="set_rule" label-width="130px">
            <el-form-item label="规格模板名称：" prop="rule_name">
                <el-input v-model="addRuleForm.rule_name" style="width: 200px;" placeholder="请输入标题名称" />
            </el-form-item>
            <div>
                <template v-for="(item, index) in spec">
                    <el-form-item>
                        <el-tag closable type="info" @close="handleValueClose(item.value, spec)">
                            {{ item.value }}
                        </el-tag>
                    </el-form-item>
                    <el-form-item>
                        <div style="display: flex;flex-wrap: wrap; align-items: flex-start;justify-content: flex-start;">
                            <el-tag v-for="tag in item.detail" :key="tag" closable :disable-transitions="false"
                                class="tag-detail" @close="handleSpecNameClose(tag, item.detail)"
                                style="margin-right: 15px;margin-bottom: 20px;">
                                {{ tag }}
                            </el-tag>
                            <el-input placeholder="请输入属性名称" class="input-with-select" ref="InputRef"
                                v-model="inputValue[index]" style="width: 200px;">
                                <template #append>
                                    <el-button @click="handleInputConfirm(item.detail, index)">添加</el-button>
                                </template>
                            </el-input>
                        </div>
                    </el-form-item>
                </template>
            </div>
            <el-form-item v-show="rule_content">
                <el-button type="primary" icon="Plus" @click="handleAddNewRule">添加新规格</el-button>
            </el-form-item>
            <div class="add-new-rules" v-show="!rule_content">
                <el-form-item label="规格名称：">
                    <el-input v-model="value" placeholder="请输入规格" />
                </el-form-item>
                <el-form-item label="规格值：">
                    <el-input v-model="ruleNum" placeholder="请输入规格值" />
                </el-form-item>
                <el-button type="primary" @click="addNewSpecs">确定</el-button>
                <el-button @click="rule_content = true">取消</el-button>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button v-show="!id" type="primary" @click="handleAddGoodsRule">
                    确定
                </el-button>
                <el-button v-show="id" type="primary" @click="handleEditGoodsRule">
                    保存
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="less" scoped>
.table {
    margin-top: 20px;
}

.add-new-rules {
    display: flex;
    justify-content: space-around;
}
</style>